package com.huaxia.service.impl;

import com.github.pagehelper.PageHelper;
import com.huaxia.base.BaseMapper;
import com.huaxia.constant.ResultConstant;
import com.huaxia.controller.MainController;
import com.huaxia.dao.OrderMapper;
import com.huaxia.exception.BusiException;
import com.huaxia.model.CountVo;
import com.huaxia.model.Order;
import com.huaxia.model.OrderPage;
import com.huaxia.model.ResultInfo;
import com.huaxia.service.OrderService;
import com.huaxia.util.AssertUtil;
import com.huaxia.util.DateUtils;
import com.huaxia.util.PageList;
import com.huaxia.util.StrUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/8/5.
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static final Log logger = LogFactory.getLog(OrderServiceImpl.class);
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public ResultInfo queryOrderList(OrderPage order) throws Exception {
        ResultInfo resultInfo = new ResultInfo();
        List<Order> result = null;
        try {
            PageHelper.startPage(order.getPageNum(),order.getPageSize());
            result =  orderMapper.queryOrderList(order);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusiException();
        }
        PageList pageList = new PageList(result);

        resultInfo.setCode(ResultConstant.OPS_SUCCESS_CODE);
        resultInfo.setMsg(ResultConstant.OPS_SUCCESS_MSG);
        resultInfo.setResult(pageList);
        return resultInfo;
    }

    @Override
    public ResultInfo queryCondtion(String orderDate) throws Exception {

        List<Map<String,Object>> resultList = new ArrayList<>();

        if (StringUtils.isEmpty(orderDate)) {
            List<String> list = orderMapper.queryAllDate();
            for (String date : list) {
                List<Map<String,Object>> result = orderMapper.queryCondtion(date);
                Map<String,Object> map = new HashMap<>();
                map.put("orderDate",date);
                map.put("orderPlay",result);
                resultList.add(map);
            }
        } else {
            List<Map<String,Object>> result = orderMapper.queryCondtion(orderDate);
            Map<String,Object> map = new HashMap<>();
            map.put("orderDate",orderDate);
            map.put("orderPlay",result);
            resultList.add(map);
        }

        ResultInfo resultInfo = new ResultInfo();
        resultInfo.setCode(ResultConstant.OPS_SUCCESS_CODE);
        resultInfo.setMsg(ResultConstant.OPS_SUCCESS_MSG);
        resultInfo.setResult(resultList);
        return resultInfo;
    }

    @Override
    @Transactional
    public ResultInfo insertSelective(Order order) throws Exception {
        if (order == null
            || StringUtils.isEmpty(order.getUserName())
            || StringUtils.isEmpty(order.getUserPhone())
            || StringUtils.isEmpty(order.getOrderPlay())
            || order.getOrderDate() == null
            ) {
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setCode(ResultConstant.PARAM_FAIL_CODE);
            resultInfo.setMsg(ResultConstant.PARAM_FAIL_MSG);
            return resultInfo;
        }
        String date = DateUtils.formatDate(order.getOrderDate());
        Map<String,String> timeMap  = orderMapper.queryTimeByPlay(order.getOrderPlay());
        String time = timeMap.get("orderTime");
        time = date+" "+time;
        logger.info("预约的场次时间是："+time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date orderDate = format.parse(time);
        Date now = new Date();
        Boolean flag = orderDate.before(now);
        if (flag) {
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setCode(ResultConstant.ORDER_TIME_ERROR_CODE);
            resultInfo.setMsg(ResultConstant.ORDER_TIME_ERROR_MSG);
            return resultInfo;
        }
        Long row = null;
        Order obj = new Order();
        obj.setUserPhone(order.getUserPhone());
//        obj.setOrderDate(order.getOrderDate());
//        obj.setOrderPlay(order.getOrderPlay());
        //先判断预约记录是不是已经存在了
        List<Order> data = orderMapper.queryOrderList(obj);
        if (data != null && data.size() > 0) {
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setCode(ResultConstant.DUP_COMMIT_CODE);
            resultInfo.setMsg(ResultConstant.DUP_COMMIT_MSG);
            return resultInfo;
        }
        try {
            order.setCreateTime(new Date());
             row = orderMapper.insertSelective(order);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusiException(ResultConstant.OPS_FAILED_MSG);
        }
        AssertUtil.isTrue(row == null || row.intValue()<1,ResultConstant.OPS_FAILED_MSG);
        String code = StrUtil.getOrderCode();
        List<String> list = orderMapper.queryOrderCode(code);
        while ( list.size()>1) {
            code = StrUtil.getOrderCode();
            System.out.println("预约码："+code);
            list = orderMapper.queryOrderCode(code);
        }
        Long row2 = new Long(0);
        row2 = orderMapper.insertOrderCode(code);
        ResultInfo result = null;
        if (row2 < 1) {
            throw new BusiException("插入预约码失败了");
        }
        order.setOrderCode(code);
        Long row3 = orderMapper.createOrderCode(order);
        if (row3 < 0) {
            throw new BusiException("创建预约码失败");
        }
        logger.info("创建预约码成功了。。。");
        result = new ResultInfo();
        result.setCode(ResultConstant.OPS_SUCCESS_CODE);
        result.setMsg(ResultConstant.OPS_SUCCESS_MSG);
        Map<String,Object> map = new HashMap<>();
        map.put("orderCode",code);
        result.setResult(map);
        return result;
    }

    @Override
    public ResultInfo updateByCondition(Order order) throws Exception {
        Long row = null;
        ResultInfo resultInfo = null;
        //根据预约码 记录才是唯一的
        if (order == null || StringUtils.isEmpty(order.getUserPhone())
            || order.getOrderDate() == null || StringUtils.isEmpty(order.getOrderPlay())) {
            resultInfo = new ResultInfo();
            resultInfo.setCode(ResultConstant.PARAM_FAIL_CODE);
            resultInfo.setMsg(ResultConstant.PARAM_FAIL_MSG);
            return resultInfo;
        }
        try {
            order.setSignIn(null);
            order.setSource(null);
           row  = orderMapper.updateByCondition(order);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusiException(ResultConstant.OPS_FAILED_MSG);
        }
        AssertUtil.isTrue(row == null,ResultConstant.OPS_FAILED_MSG);
        int r = row.intValue();
        ResultInfo result = dealResult(r);
        return result;
    }

    @Override
    public ResultInfo signIn(Order order) throws Exception {
        ResultInfo resultInfo = null;
        //根据预约码 记录才是唯一的
        if (order == null || (StringUtils.isEmpty(order.getOrderCode())
                && (StringUtils.isEmpty(order.getUserPhone()))
            )) {
            resultInfo = new ResultInfo();
            resultInfo.setCode(ResultConstant.PARAM_FAIL_CODE);
            resultInfo.setMsg(ResultConstant.PARAM_FAIL_MSG);
            return resultInfo;
        }
        order.setSignIn(new Integer(1));
        Long row = null;
        try {
             row = orderMapper.updateByCondition(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (row == null) {
            row = new Long(0);
        }
        resultInfo = dealResult(row.intValue());
        return resultInfo;
    }

    @Override
    public ResultInfo statistic(String type) throws Exception {
        List<CountVo> result = null;
        Map<String,Object> map = new HashMap<>();
        try {
            if (StringUtils.isEmpty(type) || "0".equals(type)) {
                //根据场次日期统计
                result = orderMapper.countByDate();
                map.put("desc","根据预约场次的日期统计");
            } else if ("1".equals(type)) {
                //根据来源统计
                result = orderMapper.countBySource();
                map.put("desc","根据公众号来源统计");
            } else if ("2".equals(type)) {
                //根据某天所有场次各来源 预约情况统计
                result = orderMapper.countByDateAndSource();
                map.put("desc","根据某天所有场次各来源预约情况统计");
            } else {
                //根据提交预约的日期统计
                result = orderMapper.countByCreateTime();
                map.put("desc","根据提交预约的日期统计");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResultInfo resultInfo = dealResult(0);
            return resultInfo;
        }
        ResultInfo resultInfo = new ResultInfo();
        resultInfo.setCode(ResultConstant.OPS_SUCCESS_CODE);
        resultInfo.setMsg(ResultConstant.OPS_SUCCESS_MSG);
        map.put("result",result);
        resultInfo.setResult(map);
        return resultInfo;
    }

    private ResultInfo dealResult(int row) {
        ResultInfo resultInfo = new ResultInfo();
        Map<String,String> result = new HashMap<>();
        if (row>0) {
            resultInfo.setCode(ResultConstant.OPS_SUCCESS_CODE);
            resultInfo.setMsg(ResultConstant.OPS_SUCCESS_MSG);
            result.put("status","成功");
            resultInfo.setResult(result);
            return resultInfo;
        }
        resultInfo.setCode(ResultConstant.OPS_FAILED_CODE);
        resultInfo.setMsg(ResultConstant.OPS_FAILED_MSG);
        result.put("status","失败");
        resultInfo.setResult(result);
        return resultInfo;
    }

}
